package com.kexio.websocket.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.socket.config.annotation.EnableWebSocket;

import com.kexio.websocket.handler.WebSocketHandler;
import com.kexio.websocket.interceptor.WebSocketAuthInterceptor;
import com.kexio.websocket.service.WebSocketSessionService;

/**
 * WebSocket 自动配置类
 * 
 * 自动配置 WebSocket 相关组件，支持条件装配。
 * 
 * @author Kexio Team
 */
@Configuration
@ConditionalOnClass({org.springframework.web.socket.WebSocketHandler.class})
@ConditionalOnProperty(prefix = "kexio.websocket", name = "enabled", havingValue = "true", matchIfMissing = true)
@EnableWebSocket
@EnableScheduling
public class WebSocketAutoConfiguration {

    private static final Logger log = LoggerFactory.getLogger(WebSocketAutoConfiguration.class);

    public WebSocketAutoConfiguration() {
        log.info("========================================");
        log.info("🚀 Kexio WebSocket 模块正在初始化...");
        log.info("========================================");
    }

    @Bean
    @ConditionalOnMissingBean
    public WebSocketSessionService webSocketSessionService() {
        log.info("✅ 注册 WebSocketSessionService");
        return new WebSocketSessionService();
    }

    @Bean
    @ConditionalOnMissingBean
    public WebSocketAuthInterceptor webSocketAuthInterceptor() {
        log.info("✅ 注册 WebSocketAuthInterceptor");
        return new WebSocketAuthInterceptor();
    }

    @Bean
    @ConditionalOnMissingBean
    public WebSocketHandler webSocketHandler() {
        log.info("✅ 注册 WebSocketHandler");
        return new WebSocketHandler();
    }


    @Bean
    @ConditionalOnMissingBean
    public WebSocketConfig webSocketConfig() {
        log.info("✅ 注册 WebSocketConfig - WebSocket 端点: /api/ws");
        return new WebSocketConfig();
    }

    /**
     * 定时清理已关闭的 WebSocket 会话
     */
    @Scheduled(fixedRate = 60000) // 每分钟执行一次
    public void cleanupWebSocketSessions() {
        try {
            WebSocketSessionService sessionService = webSocketSessionService();
            sessionService.cleanupClosedSessions();
            
            // 记录统计信息
            WebSocketSessionService.WebSocketStats stats = sessionService.getStats();
            if (stats.getOnlineUsers() > 0) {
                log.debug("WebSocket 会话统计: 在线用户={}, 活跃会话={}", 
                        stats.getOnlineUsers(), stats.getActiveSessions());
            }
        } catch (Exception e) {
            log.error("清理 WebSocket 会话失败: {}", e.getMessage(), e);
        }
    }
}
